// pages/material/pages/basis/client_a/index.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        modify: false, //判断是否是修改
        on_index: '', //当前修改的索引
        //委托人资料
        full_name: '', //姓名
        phone_number: '', //电话
        idCard_z: '', //身份证（正）
        idCard_f: '', //身份证（反）
        household: '', //户口本
        household_files: [], //户口本
        household_max: 9,
        household_max_vir: 9, //最多上传张数 
        image_src: {
        },

    },
    set_input: function (e) {},
    //图片选择
    choose_images: function (e) {
        var that = this;
        let source = e.currentTarget.dataset.source; //当前占位图名字
        let type = e.currentTarget.dataset.type; // 类型（单图/多图）
        if (type == 0) { //单图
            wx.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths
                    var upload_img = source
                    that.setData({
                        [upload_img]: src
                    });
                    var tempFilePaths = res.tempFilePaths
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        wx.uploadFile({
                            url: 'https://gz.gzrzvisa.com/data/api.upload/add',
                            filePath: tempFilePaths[i],
                            name: "file",
                            header: {
                                "content-type": "multipart/form-data"
                            },
                            success: function (res) {
                                
                                if (res.statusCode == 200) {
                                    wx.showToast({
                                        title: "上传成功",
                                        icon: "none",
                                        duration: 1500
                                    })
                        
                                    that.data.image_src[upload_img] = res.data
                                    // console.log(that.data.image_src[upload_img]);
                                }
                            },
                            fail: function (err) {
                                wx.showToast({
                                title: "上传失败",
                                icon: "none",
                                duration: 2000
                                })
                            },
                            complete: function (result) {
                                console.log(result.errMsg)
                            }
                        })
                    }
                }
            });
        } else if (type == 1) { //多图
            var in_source = source + '_files'; //当前占位图名字
            let in_count = source + '_max_vir'; //当前占位图名字
            let num_vir = e.currentTarget.dataset.num_vir; //限制数值
            wx.chooseImage({
                count: num_vir,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths;
                    console.log(src)
                    that.setData({
                        [in_count]: num_vir + 1,
                        [in_source]: that.data[in_source].concat(src)
                    });
                    var tempFilePaths = res.tempFilePaths
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        wx.uploadFile({
                            url: 'https://gz.gzrzvisa.com/data/api.upload/add',
                            filePath: tempFilePaths[i],
                            name: "file",
                            header: {
                                "content-type": "multipart/form-data"
                            },
                            success: function (res) {
                                if (res.statusCode == 200) {
                                    wx.showToast({
                                        title: "上传成功",
                                        icon: "none",
                                        duration: 1500
                                    })
                        
                                    if(typeof(that.data.image_src[in_source]) == 'undefined'){
                                        that.data.image_src[in_source] = [];
                                    }
                                    that.data.image_src[in_source] = that.data.image_src[in_source].concat(res.data)
                                    // console.log(that.data.image_src[in_source]);
                                }
                            },
                            fail: function (err) {
                                wx.showToast({
                                title: "上传失败",
                                icon: "none",
                                duration: 2000
                                })
                            },
                            complete: function (result) {
                                console.log(result.errMsg)
                            }
                        })
                    }
                }
            });
        }
    },
    //删除图片
    to_delete: function (e) {
        console.log(e)
        var that = this;
        var select_type = e.currentTarget.dataset.source; //当前占位图名字
        that.setData({
            [select_type]:'',
        });
        that.data.image_src[select_type] = '';
        console.log(that.data.image_src);
    },
    //查看图片
    previewImage: function (e) {
        var source = e.currentTarget.dataset.source;
        wx.previewImage({
            current: e.currentTarget.source, // 当前显示图片的http链接
            urls: source // 需要预览的图片http链接列表
        })
    },
        //多图查看图片
        preview_image: function (e) {
            var that = this
            let files = e.currentTarget.dataset.source
            var img = e.currentTarget.dataset.img
            wx.previewImage({
                current: img, // 当前显示图片的http链接
                urls: that.data[files] // 需要预览的图片http链接列表
            })
        },
        //多图删除
        delete_set: function (e) {
            console.log(e)
            var that = this;
            let source = e.currentTarget.dataset.source;
            var in_source = source + '_files'; //当前占位图名字
            let in_count = source + '_max_vir'; //当前占位图名字
            let num_vir = e.currentTarget.dataset.num_vir; //限制数值
            let index = e.currentTarget.dataset.index;
            let images = that.data[in_source];
            images.splice(index, 1);
            that.setData({
                [in_count]: that.data.photo_count + 1,
                [in_source]: images,
            });
            that.data.image_src[in_source].splice(index, 1)
        },
    //提交
    to_submit: function (e) {
        var that = this;
        let full_name = that.data.full_name; //姓名
        let phone_number = that.data.phone_number; //电话
        let idCard_z = that.data.idCard_z; //身份证（正）
        let idCard_f = that.data.idCard_f; //身份证（反）
        let household_files = that.data.household_files; //户口本
        let image_src = that.data.image_src;
        console.log(image_src);
        if (full_name == '') {
            wx.showToast({
                title: '请填写委托人姓名',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (phone_number === '') {
            wx.showToast({
                title: '请填写委托人联系电话',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (!(/^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(phone_number))) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none',
                mask: true,
                duration: 1500
            });
            return
        } else if (idCard_z === '') {
            wx.showToast({
                title: '请上传身份证正面照',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (idCard_f === '') {
            wx.showToast({
                title: '请上传身份证背面照',
                icon: 'none',
                mask: false,
            });
            return false;
        }  
        // else if (household_files.length<=0 ) {
        //     wx.showToast({
        //         title: '请上传户口本图片',
        //         icon: 'none',
        //         mask: false,
        //     });
        //     return false;
        // }
        this.setData({
            disabled: true
        })
        var modify = that.data.modify;
        var on_index = that.data.on_index; //当前修改数据的索引值
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        console.log(prevPage);
        var client_list = prevPage.data.client_list;
        if (modify == false) { //【添加数据】
            var newData = {
                full_name: full_name, //姓名
                phone_number: phone_number, //电话
                idCard_z: idCard_z, //身份证（正）
                idCard_f: idCard_f, //身份证（反）
                household_files: household_files, //户口本
                image_src:image_src,

            };
            client_list.push(newData); //实质是添加lists数组内容，使for循环多一次
            prevPage.setData({
                client_list: client_list,
                no_list: false
            })
        } else { //【修改数据】
            var newData = {
                
                full_name: full_name, //姓名
                phone_number: phone_number, //电话
                idCard_z: idCard_z, //身份证（正）
                idCard_f: idCard_f, //身份证（反）
                household_files: household_files, //户口本
                image_src:image_src,
            };
            prevPage.setData({
                [`client_list[${on_index}]`]: newData
            })
        }
        wx.showToast({
            title: '上传中...',
            icon: 'loading',
            mask: true,
            duration: 1500,
            success(res) {
                setTimeout(() => { //上传成功后pages/material/pages/attest/index
                    wx.navigateBack({
                        delta: 0
                    })
                }, 1500)
            }
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面
        var client_list = prevPage.data.client_list;
        console.log(client_list)
        if (typeof (options.index) != 'undefined') {
            wx.setNavigationBarTitle({
                title: '修改委托人信息'
            })
            that.setData({
                modify: true,
                on_index: options.index,
                full_name: client_list[options.index].full_name, //姓名
                phone_number: client_list[options.index].phone_number, //电话
                idCard_z: client_list[options.index].idCard_z, //身份证（正）
                idCard_f: client_list[options.index].idCard_f, //身份证（反）
                household_files: client_list[options.index].household_files, //户口本
                image_src: client_list[options.index].image_src, //集合
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})